# TMP
import os
import locale
language, output_encoding = locale.getdefaultlocale()
from BeautifulSoup import BeautifulSoup

import re
import urllib2

# Configuration variables
basedir = "E:/downloads/TV"

downloadedFilesRegexp = r"""
(?P<show>.*?)\.                     # Show title
# BEGIN season/episode matching
[sS]?(?P<season>[0-9]{1,2})[eE]?(?P<episode>[0-9]{2}) # sXXeYY, XXeYY, SXXEYY, XXYY
    (?:-[eE](?P<episode2>[0-9]{2}))? #-eAA (double eps)
# END season/episode matching
\.(?P<misc>[^\-]*)  # misc (title, def, etc)
-([a-zA-Z0-9]+)     # group
\.(mkv|avi)         # extension
"""
subtitleFileRegexp = 'S([0-9]+)E([0-9]+(-[0-9]+)?)'
languageRegexp = r"""
\.
(fr|en|ENFR|VF|VO)
[\.\(]
"""

languagesMap = {'ENFR':['en','fr'], 'VO':'en','VF':'fr','fr':'fr','en':'en'}

TVShowParser = re.compile( downloadedFilesRegexp, re.VERBOSE )
BSShowCleaner = re.compile( '[^a-zA-Z]' )
TVShowFiles = os.listdir( basedir )
for fileName in TVShowFiles:

    matches = TVShowParser.match( fileName )
    if not matches:
        continue
    #if matches == null:
    #   continue
    BSShowName = BSShowCleaner.sub( '',  matches.group( 'show' ) ).lower()
    print BSShowName
    
    url = "http://www.betaseries.com/ajax/soustitres.php?url=" + BSShowName + "&saison=" + matches.group( 'season' )
    print "URL:" + url
    usock = urllib2.urlopen( url )
    data = usock.read()
    usock.close()
    
    soup = BeautifulSoup( data )
    episodeMatcher = re.compile( subtitleFileRegexp )
    subtitleMatcher = re.compile( languageRegexp, re.VERBOSE )
    subtitles = []
    
    for div in soup.findAll( 'div', attrs = { 'class':'item' } ):
        
        detailNode = div.findAll( 'div', attrs = { 'class':'details' } )
        episodeString = detailNode[0].contents[0].string.strip();
        episodeStringMatches = episodeMatcher.match( episodeString )
        seasonNumber = episodeStringMatches.group( 1 )
        episodeNumber = episodeStringMatches.group( 2 )
        subtitle = subtitleFile()
        subtitle.episodeNumber = episodeNumber
        subtitle.seasonNumber = seasonNumber

        for div2 in div.findAll( 'div', attrs = { 'class':'download' } ):
            try:
                fileName = div2.a.string.strip()
                url = div2.a["href"]
                
            except Exception:
                continue

            subtitle.filename = fileName

            # Language
            languageMatches = subtitleMatcher.search( fileName )
            if languageMatches is not None:
                subtitle.language = languagesMap[languageMatches.group(1)]
            else:
                print "No language in " + fileName

            subtitle.url = url
            subtitles.append( subtitle )

    for subtitle in subtitles:
        print subtitle

